#include "delay.h"
#include "stm32f4xx.h"

void TIM3_Init(uint16_t arr, uint16_t psc)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

    TIM_TimeBaseInitStructure.TIM_Prescaler      = psc;
    TIM_TimeBaseInitStructure.TIM_CounterMode    = TIM_CounterMode_Down;
    TIM_TimeBaseInitStructure.TIM_Period         = arr;
    TIM_TimeBaseInitStructure.TIM_ClockDivision  = TIM_CKD_DIV1;

    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
}

int Delay_Init(void)
{
    TIM3_Init(100 - 1, 84 - 1);
    return 0;
}

void Delay_Us(uint32_t us)
{
    TIM3->ARR = us;
    TIM3->CNT = TIM3->ARR;
    TIM_Cmd(TIM3, ENABLE);
    while(TIM3->CNT) {;}
    TIM_Cmd(TIM3, DISABLE);
}

void Delay_Ms(uint32_t ms)
{
    for(int i = 0; i < ms; i++){
        Delay_Us(1000);
    }
}
